package com.katze.common;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.katze.common.config.MybatisPlusConfiguration;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Pagination implements Serializable {

    private static final long serialVersionUID = -4869594085374385813L;
    private static final Pattern humpPattern = Pattern.compile("[A-Z]");

    private boolean enabled;

    private int pageSize = 10;
    private int pageNum = 1;

    private String sort;
    private String order;

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public void setOrder(String order) {
        this.order = order;
    }

    public <T>Page<T> toPage(OrderItem... defaultOrder) {
        if (pageNum == 0) return null;
        Page<T> page = PageDTO.of(pageNum, pageSize);
        if (StringUtils.isNotBlank(this.sort) && StringUtils.isNotBlank(this.order)) {
            String field = MybatisPlusConfiguration.isMapUnderscoreToCamelCase()? camelToUnderscore(this.sort):this.sort;
            OrderItem order = this.order.startsWith("desc") ? OrderItem.desc(field) : OrderItem.asc(field);
            page.orders().add(order);
        } else {
            for (OrderItem orderItem : defaultOrder) {
                page.orders().add(orderItem);
            }
        }
        return page;
    }

    private String camelToUnderscore(String value) {
        if (StringUtils.isBlank(value)) return value;
        Matcher matcher = humpPattern.matcher(value);
        while (matcher.find()) {
            value = value.replace(matcher.group(0), "_" + matcher.group(0).toLowerCase());
        }
        return value;

    }

    @Override
    public String toString() {
        return "QueryRequest{" +
                "pageSize=" + pageSize +
                ", pageNum=" + pageNum +
                ", sort='" + sort + '\'' +
                ", order='" + order + '\'' +
                ", enabled='" + enabled + '\'' +
                '}';
    }
}
